<template>
  <div class="visualization-container">
    <div class="header">
      <h2>数据可视化</h2>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon size="24" color="white"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.literatureCount }}</div>
              <div class="stat-label">文献总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon size="24" color="white"><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.favoriteCount }}</div>
              <div class="stat-label">收藏文献</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon size="24" color="white"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.categoryCount }}</div>
              <div class="stat-label">文献分类</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon size="24" color="white"><DataAnalysis /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.keywordCount }}</div>
              <div class="stat-label">关键词数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-container">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>关键词统计</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="categoryChartRef" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>文献发表趋势</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <div ref="trendChartRef" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 关键词云图 -->
    <el-row :gutter="20" class="keyword-section">
      <el-col :span="24">
        <el-card class="keyword-card">
          <template #header>
            <div class="keyword-header">
              <span>热门关键词</span>
            </div>
          </template>
          <div class="keyword-cloud">
            <div 
              v-for="(item, index) in keywordData" 
              :key="index"
              class="keyword-item"
              :style="{ fontSize: item.size + 'px', color: item.color }"
            >
              {{ item.keyword }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { Document, Star, TrendCharts, DataAnalysis } from '@element-plus/icons-vue'
import { visualizationApi } from '@/api/visualization'
import { literatureApi } from '@/api/literature'
import type { KeywordStatisticsRequest, KeywordStatItem, LiteratureTrendRequest, TrendItem } from '@/api/visualization'
import type { Literature, PageResult } from '@/api/literature'

// 图表引用
const categoryChartRef = ref<HTMLDivElement | null>(null)
const trendChartRef = ref<HTMLDivElement | null>(null)

// 统计数据
const stats = ref({
  literatureCount: 0,
  favoriteCount: 0,
  categoryCount: 0,
  keywordCount: 0 as number | string
})

// 关键词数据
const keywordData = ref<Array<{ keyword: string; size: number; color: string }>>([])

// 图表实例
let categoryChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null

// 定时器
let refreshTimer: number | null = null

// 初始化图表
const initCharts = () => {
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
  }
  
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
  }
  
  // 监听窗口大小变化，自适应图表
  window.addEventListener('resize', () => {
    categoryChart?.resize()
    trendChart?.resize()
  })
}

// 获取统计数据
const fetchStats = async () => {
  try {
    // 获取文献总数
    const literatureResponse: PageResult<Literature> = await literatureApi.getList({ size: 1 })
    stats.value.literatureCount = literatureResponse.total
    
    // 获取收藏文献数
    const favoriteResponse: PageResult<Literature> = await literatureApi.getFavorites({ size: 1 })
    stats.value.favoriteCount = favoriteResponse.total
    
    // 获取分类数和关键词数（从真实数据获取）
    try {
      const categoryRequest: KeywordStatisticsRequest = {
        limit: 100  // 获取所有分类
      }
      
      const categoryResponse = await visualizationApi.getKeywordStatistics(categoryRequest)
      
      // 统计不同的分类数量
      const categories = new Set(categoryResponse.items.map(item => item.category).filter(category => category))
      stats.value.categoryCount = categories.size
      
      // 关键词数量，大于999显示999+
      const keywordCount = categoryResponse.items.length;
      stats.value.keywordCount = keywordCount > 999 ? '999+' : keywordCount;
    } catch (error) {
      console.warn('获取分类和关键词统计失败:', error)
      // 如果获取失败，使用模拟数据
      stats.value.categoryCount = 12
      stats.value.keywordCount = 156
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取分类统计数据
const fetchCategoryData = async () => {
  try {
    const request: KeywordStatisticsRequest = {
      limit: 10
    }
    
    const response = await visualizationApi.getKeywordStatistics(request)
    
    // 准备饼图数据
    const chartData = response.items.map(item => ({
      name: item.keyword,
      value: item.count
    }))
    
    // 更新图表
    if (categoryChart) {
      categoryChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '文献分类',
            type: 'pie',
            radius: '50%',
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

// 获取趋势数据
const fetchTrendData = async () => {
  try {
    const request: LiteratureTrendRequest = {
      granularity: 'day',
      startDate: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 最近一周
      endDate: new Date().toISOString().split('T')[0]
    }
    
    // 调用趋势API获取真实数据
    const response = await visualizationApi.getLiteratureTrend(request)
    
    // 准备折线图数据
    const xAxisData = response.items.map(item => item.timePoint)
    const seriesData = response.items.map(item => item.count)
    
    // 更新图表
    if (trendChart) {
      trendChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '文献数量',
            type: 'line',
            data: seriesData,
            smooth: true,
            areaStyle: {}
          }
        ]
      })
    }
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

// 生成关键词云数据
const generateKeywordCloud = async () => {
  try {
    const request: KeywordStatisticsRequest = {
      limit: 20
    }
    
    const response = await visualizationApi.getKeywordStatistics(request)
    
    const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
    
    keywordData.value = response.items.map((item, index) => ({
      keyword: item.keyword,
      size: Math.floor(item.count * 5) + 16, // 根据出现次数调整字体大小
      color: colors[Math.floor(Math.random() * colors.length)]
    }))
  } catch (error) {
    console.error('获取关键词云数据失败:', error)
    // 如果获取失败，使用模拟数据
    const keywords = [
      '癌症治疗', '药物研发', '基因编辑', '免疫疗法', '临床试验',
      '医学影像', '人工智能', '大数据', '精准医疗', '远程医疗',
      '生物技术', '纳米医学', '再生医学', '个性化治疗', '预防医学'
    ]
    
    const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
    
    keywordData.value = keywords.map(keyword => ({
      keyword,
      size: Math.floor(Math.random() * 20) + 16,
      color: colors[Math.floor(Math.random() * colors.length)]
    }))
  }
}

// 刷新数据
const refreshData = () => {
  fetchStats()
  fetchCategoryData()
  fetchTrendData()
  generateKeywordCloud()
}

// 开始定时刷新
const startAutoRefresh = () => {
  // 每30秒刷新一次数据
  refreshTimer = window.setInterval(() => {
    refreshData()
  }, 30000)
}

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    window.clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(() => {
  nextTick(() => {
    initCharts()
    refreshData()
  })
  
  // 开始定时刷新
  startAutoRefresh()
})

onUnmounted(() => {
  // 停止定时刷新
  stopAutoRefresh()
  
  // 销毁图表实例
  if (categoryChart) {
    categoryChart.dispose()
    categoryChart = null
  }
  
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
})
</script>

<style scoped>
.visualization-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.chart-header {
  font-weight: bold;
  color: #303133;
}

.chart-wrapper {
  padding: 20px 0;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.keyword-section {
  margin-bottom: 20px;
}

.keyword-card {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.keyword-header {
  font-weight: bold;
  color: #303133;
}

.keyword-cloud {
  padding: 20px;
  text-align: center;
  min-height: 200px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.keyword-item {
  display: inline-block;
  cursor: pointer;
  transition: transform 0.2s;
}

.keyword-item:hover {
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-overview .el-col,
  .charts-container .el-col {
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .keyword-cloud {
    min-height: 150px;
  }
}
</style>